package com.qiku.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

@Component
public class BlackListFilter implements GlobalFilter , Ordered {

    @Value("${server.port}")
    private String port;

    // 模拟黑名单
    private static List<String> blackList = new ArrayList<>();

    // 使用静态代码块添加黑名单  静态代码块只能访问静态成员  只能访问静态成员变量
    static {
//        blackList.add("192.168.0.171");  // 本机
//        blackList.add("0:0:0:0:0:0:0:1"); // 本机IP
        blackList.add("192.168.0.172");
        blackList.add("192.168.0.173");
        blackList.add("192.168.0.174");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("当前网关端口号:==" + port);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取客户端ip
        InetSocketAddress ip = request.getRemoteAddress();
        System.out.println("当前机器ip地址+++===" + ip.getHostString());

        if (blackList.contains(ip.getHostString())){
            // 拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码  无权限
            System.out.println("黑名单成员，无法访问 ~~");
            // 准备响应信息
            String data = "Request be denied";
            // 将信息进一步的封装
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            // 将封装后的信息响应
            return response.writeWith(Mono.just(wrap));
        }
        // 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
